package com.lxw.weather.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import java.util.ArrayList;

import com.lxw.weather.R;

public class CityManagerActivity extends AppCompatActivity {
    private SQLiteDatabase db;
    private CityAdapter adapter;
    private String currentCity;
    private List<String> cityDataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_manager);

        // 添加ActionBar返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("城市管理");
        }

        // 初始化数据库
        SQLiteOpenHelper dbHelper = new SQLiteOpenHelper(this, "city_db", null, 1) {
            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL("CREATE TABLE cities (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                db.execSQL("DROP TABLE IF EXISTS cities");
                onCreate(db);
            }
        };

        db = dbHelper.getWritableDatabase();

        // 初始化UI组件
        EditText cityInput = findViewById(R.id.city_input);
        Button addButton = findViewById(R.id.add_button);
        ListView cityList = findViewById(R.id.city_list);

        // 初始化适配器
        this.adapter = new CityAdapter(this, cityDataList);
        cityList.setAdapter(adapter);

        // 加载城市列表数据
        loadCities();

        // 设置添加按钮点击事件
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String cityName = cityInput.getText().toString().trim();
                if (!cityName.isEmpty()) {
                    addCity(cityName);
                    cityInput.setText(""); // 清空输入框
                } else {
                    Toast.makeText(CityManagerActivity.this, "请输入城市名称", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 设置列表项点击事件 - 选择城市
        cityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentCity = adapter.getItem(position);
                Intent resultIntent = new Intent();
                resultIntent.putExtra("selectedCity", currentCity);
                setResult(RESULT_OK, resultIntent);
                finish();
            }
        });
    }

    // 修改自定义适配器类
    private class CityAdapter extends ArrayAdapter<String> {
        public CityAdapter(CityManagerActivity context, List<String> cities) {
            super(context, R.layout.city_item, R.id.city_name, cities);
        }
    
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            
            // 删除按钮逻辑
            Button deleteButton = view.findViewById(R.id.delete_button);
            deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String cityName = getItem(position);
                    deleteCity(cityName);
                }
            });
            
            // 常驻地按钮逻辑
            Button defaultButton = view.findViewById(R.id.default_button);
            defaultButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String cityName = getItem(position);
                    // 保存为默认城市
                    getSharedPreferences("weather_prefs", MODE_PRIVATE)
                        .edit()
                        .putString("default_city", cityName)
                        .apply();
                    Toast.makeText(CityManagerActivity.this, cityName + " 已设为常驻地", Toast.LENGTH_SHORT).show();
                }
            });
            
            return view;
        }
    }

    // 加载城市列表
    private void loadCities() {
        adapter.clear();
        try (Cursor cursor = db.query("cities",
                new String[]{"name"},
                null, null, null, null, null)) {
            while (cursor.moveToNext()) {
                adapter.add(cursor.getString(0));
            }
        }
        // 通知适配器数据变化
        adapter.notifyDataSetChanged();
    }

    // 检查城市是否已存在
    private boolean isCityExist(String cityName) {
        boolean exists = false;
        Cursor cursor = null;
        try {
            cursor = db.query("cities",
                    new String[]{"name"},
                    "name=?",
                    new String[]{cityName},
                    null, null, null);
            exists = cursor.getCount() > 0;
        } finally {
            if (cursor != null) cursor.close();
        }
        return exists;
    }

    // 添加城市
    public void addCity(String cityName) {
        if(isCityExist(cityName)) {
            Toast.makeText(this, "城市已存在", Toast.LENGTH_SHORT).show();
            return;
        }

        ContentValues values = new ContentValues();
        values.put("name", cityName);
        long result = db.insert("cities", null, values);

        if (result != -1) {
            loadCities();
            Toast.makeText(this, "城市添加成功", Toast.LENGTH_SHORT).show();
        }
    }

    // 删除城市
    public void deleteCity(String cityName) {
        int result = db.delete("cities", "name=?", new String[]{cityName});

        if (result > 0) {
            loadCities();
            Toast.makeText(this, "城市删除成功", Toast.LENGTH_SHORT).show();
        }
    }

    public String getCurrentCity() {
        return currentCity;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    // 添加返回按钮点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            // 返回当前选择的城市
            Intent resultIntent = new Intent();
            resultIntent.putExtra("selectedCity", currentCity);
            setResult(RESULT_OK, resultIntent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}